package com.kmust.dream.wanderingdream.product.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kmust.dream.wanderingdream.product.entity.ProductPropertyValue;
import com.kmust.dream.wanderingdream.product.entity.ProductSku;
import com.kmust.dream.wanderingdream.product.service.ProductPropertyValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
public class ParseUtils {

    @Autowired
    private ProductPropertyValueService valueService;

    private static  ParseUtils parseUtils;

    //第四步 初始化
    @PostConstruct
    public void init() {
        parseUtils = this;
    }

    //在排序的基础上生成desc
    public static String parseDescription(String keyValue) {
        List<Integer> list = changeSort(keyValue);
        QueryWrapper<ProductPropertyValue> queryWrapper = new QueryWrapper<ProductPropertyValue>().in("product_property_value_id", list);
        List<ProductPropertyValue> res = parseUtils.valueService.list(queryWrapper);
        StringBuilder sb = new StringBuilder();
        for (ProductPropertyValue re : res) {
            sb.append(re.getProductPropertyValue());
            sb.append(" ");
        }
        return sb.toString();
    }

    //改变顺序,按从小到达排序
    public static List<Integer> changeSort(String propertiesStr) {
        if (propertiesStr == null || propertiesStr.length() ==0)
            return null;
        String[] split = propertiesStr.split(":");
        List<Integer> list = new ArrayList<>();
        for (String s : split)
            list.add(Integer.valueOf(s));
        Collections.sort(list);
        return list;
    }

    public static String reChange(List<Integer> sorted) {
        StringBuilder sb = new StringBuilder();
        for (Integer integer : sorted) {
            sb.append(integer);
            sb.append(":");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    //该方法在商家添加和用户下单从orderPre中取出的sku对象的时候都要进行更新
    public static void updateSku(ProductSku sku) {
        //先改顺序，更新到productSku
        List<Integer> list = changeSort(sku.getProductSkuProperties());
        String s = reChange(list);
        sku.setProductSkuProperties(s);
        //后根据值，更新desc
        sku.setProductSkuDesc(parseDescription(s));
    }
}
